// 一维数组转潜逃JSON树
const toTree = function toTree(arr) {
    let map = {}, temp;
    while (temp = arr.pop()) {
        let obj = {};
        obj.name = temp;
        obj.child = map;
        map = obj;
    }
    return map;
}


// 数组转json树
const toTree2 = function toTree2(arr) {
    const len = arr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
            if (arr[i].pid === arr[j].id) {
                if (!(arr[j].child instanceof Array)) {
                    arr[j].child = [arr[i]];
                } else {
                    console.log(arr[j].child);
                    arr[j].child.push(arr[i]);
                }

            }
        }
    }
    return arr;
}



const arr = ['a', 'b', 'c'];
const arr2 = [{
    id: 1,
    name: 'a',
    pid: 2
}, {
    id: 2,
    name: 'b',
    pid: 3
}, {
    id: 3,
    name: 'a',
    pid: 4
}, {
    id: 4,
    name: 'c',
    pid: 5
}, {
    id: 5,
    name: 'd',
    pid: null
}]
// console.log(toTree(arr))
console.log(toTree2(arr2))
